/**
 * 
 */
package com.glela.platform.service.impl;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glela.cache.model.RedisKey;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.util.BeanCopierUtils;
import com.glela.platform.mapper.TokenMapper;
import com.glela.platform.model.Token;
import com.glela.platform.model.User;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.TokenService;
import com.glela.platform.service.UserService;

/**
 * @author liujie
 *
 */
@Service
public class TokenServiceImpl implements TokenService {

	@Resource
	private TokenMapper tokenMapper;
	
	private static Logger			logger			= LoggerFactory.getLogger(TokenServiceImpl.class);
	
	@Autowired
	RedisUtil redisUtil;
	
	@Autowired
	UserService userService;
	
	
	@Override
	public String SaveToken(ResponseUser user,String clientType) {
		Token token = tokenMapper.selectByUserId(user.getUserId(),clientType);
		if(null != token){
//			token.setDeviceid(user.getDeviceId());
			token.setCode(null);
			token.setClientType(clientType);
			if(StringUtils.equals("15221163357", user.getUserName()))token.setCode("9531eed6-b78a-4a40-9179-d9909af2ebbc"); ////保证我们测试人员的登录TOKEN在系统是一个固定值,方便进行压力测试
			
			tokenMapper.updateByPrimaryKeySelective(token);
			cacheUserToken(token.getCode(),user.getUserId(),clientType);
		}else{
			token = new Token();
			token.setCode(null);
			token.setClientType(clientType);
			if(StringUtils.equals("15221163357", user.getUserName()))token.setCode("9531eed6-b78a-4a40-9179-d9909af2ebbc"); //保证我们测试人员的登录TOKEN在系统是一个固定值,方便进行压力测试
//			token.setDeviceid(user.getDeviceId());
//			token.setStatus(1);
			token.setUserId(user.getUserId());
			
			tokenMapper.insertSelective(token);
			cacheUserToken(token.getCode(),user.getUserId(),clientType);
			
		}
		userService.cacheUser(user.getUserId());
		return token.getCode();
	}

	@Override
	public String SaveToken2(User user,String clientType) {
		// TODO Auto-generated method stub
		Token token = tokenMapper.selectByUserId(user.getId(),clientType);
		
		if(null != token){
			logger.error("H5 微信登录TOKEN已存在! clientType: {}",clientType );
//			token.setDeviceid(user.getDeviceId());
			token.setCode(null);
			token.setClientType(clientType);
			tokenMapper.updateByPrimaryKeySelective(token);
			cacheUserToken(token.getCode(),user.getId(),clientType);
		}else{
			logger.error("H5 微信登录TOKEN不存在! clientType: {}",clientType );
			token = new Token();
			token.setCode(null);
//			token.setDeviceid(user.getDeviceId());
//			token.setStatus(1);
			token.setClientType(clientType);
			token.setUserId(user.getId());
			
			tokenMapper.insertSelective(token);
			cacheUserToken(token.getCode(),user.getId(),clientType);
		}
		userService.cacheUser(user.getId());
		return token.getCode();
	}
	
	@Override
	public Token selectTokenByCode(String code,String clientType) {
		return tokenMapper.selectTokenByCode(code,clientType);
	}
	
	
	public Token selectToken(Token record) {
		return tokenMapper.selectToken(record);
	}
	
	public void cacheUserToken(String token,Long userId,String clientType) {
		String _key = RedisKey.USER_TOKEN_HASH + clientType + ":" + userId;
		Token _token = tokenMapper.selectByUserId(userId, clientType);
		if(_token != null) {
			;
			redisUtil.hmset(_key,BeanCopierUtils.objectToMap(_token));
		}
	}
	
	public Token selectTokenFormCache(Long userId,String clientType) {
		String _key = RedisKey.USER_TOKEN_HASH + clientType + ":" + userId;
		Token _token = redisUtil.hmgetToObject(_key, Token.class);
		 if(_token == null) {
			 _token = tokenMapper.selectByUserId(userId, clientType);
			 if(_token == null) {
				 return null;
			 }
			 redisUtil.hmset(_key,_token);
		 }
		 return _token;
	}
	
	public Token isLogin(Token record) {
		Token _token = selectTokenFormCache(record.getUserId() , record.getClientType());
		if(_token != null) {
			if(StringUtils.equals(_token.getCode(), record.getCode()) ) {
				return _token;
			}else {
				logger.error("过滤拦截TOKEN不一致 提交TOKEN : {}  , 从缓存中获取的TOKEN: {}", record.getCode() , _token.getCode());
				return null;
			}
		}else {
			logger.error("过滤拦截TOKEN不一致 根据提交userId 和 clientType 无法从系统缓存中获取 TOKEN对象, 提交userId: {} ,提交 clientType:  {}",  record.getUserId() ,  record.getClientType());
			return null;
		}
		
		
		
		
		
	}
}
